RiskPanel = function(viewer) {
	this.viewer = viewer;
	this.newIndex = 2;
    RiskPanel.superclass.constructor.call(this, {
        id:'risk-tree',
        region:'west',
        title:'Riesgos',
        split:true,
        width: 300,
        minSize: 200,
        maxSize: 450,
        collapsible: true,
        margins:'5 0 5 5',
        cmargins:'5 5 5 5',
        rootVisible:false,
        lines:false,
        autoScroll:true,
        root: new Ext.tree.TreeNode('Riesgos'),
        collapseFirst:false,

		animate:true,
        enableDD:true,
        containerScroll: true,
        ddGroup: 'riskDD',

        tbar: [{
            iconCls:'add',
            text:'Agregar Riesgo',
            handler: this.showNewRisk,
            scope: this
        },{
            id:'delete',
            iconCls:'remove',
            text:'Eliminar',
            handler: function(){
                var s = this.getSelectionModel().getSelectedNode();
                if(s){
                    this.removeRisk(s.attributes.url);
                }
            },
            scope: this
        }]
    });

    this.risks = this.root.appendChild(
        new Ext.tree.TreeNode({
            text:'Riesgos',
            cls:'risk-node',
            expanded:true
        })
    );

    this.getSelectionModel().on({
        'beforeselect' : function(sm, node){
             return node.isLeaf();
        },
        'selectionchange' : function(sm, node){
            if(node){
                this.fireEvent('riskselect', node.attributes);
            }
            this.getTopToolbar().items.get('delete').setDisabled(!node);
        },
        scope:this
    });

    this.addEvents({riskselect:true});

    this.on('contextmenu', this.onContextMenu, this);
};

Ext.extend(RiskPanel, Ext.tree.TreePanel, {

    onContextMenu : function(node, e){
        if(!this.menu){ // create context menu on first right click
            this.menu = new Ext.menu.Menu({
                id:'risk-ctx',
                items: [{
                    id:'details',
                    iconCls:'details',
                    text:'Ver Riesgo',
                    scope: this,
                    handler:function(){
                        this.ctxNode.select();
						this.viewer.openTab(node);
                    }
                },{
                    text:'Remove',
                    iconCls:'remove',
                    scope: this,
                    handler:function(){
                        this.ctxNode.ui.removeClass('x-node-ctx');
                        this.removeRisk(this.ctxNode.url);
                        this.ctxNode = null;
                    }
                },'-',{
                    iconCls:'add',
                    text:'Agregar Riesgo',
                    handler: this.showNewRisk,
                    scope: this
                }]
            });
            this.menu.on('hide', this.onContextHide, this);
        }
        if(this.ctxNode){
            this.ctxNode.ui.removeClass('x-node-ctx');
            this.ctxNode = null;
        }
        if(node.isLeaf()){
            this.ctxNode = node;
            this.ctxNode.ui.addClass('x-node-ctx');
            this.menu.items.get('details').setDisabled(node.isSelected());
            this.menu.showAt(e.getXY());
        }
    },

    onContextHide : function(){
        if(this.ctxNode){
            this.ctxNode.ui.removeClass('x-node-ctx');
            this.ctxNode = null;
        }
    },

	showNewRisk: function(){
		var index = ++this.newIndex;
		var node = new Ext.tree.TreeNode({
		url:' ',
		text: 'Riesgo ' + index,
		iconCls: 'feed-icon',
            leaf:true,
            cls:'feed',
            id: 'null'
		});
        this.risks.appendChild(node);
        node.select();
	},

    selectRisk: function(url){
        this.getNodeById(url).select();
    },

    removeRisk: function(url){
        var node = this.getSelectionModel().getSelectedNode();
        if(node){
			var res = this.remoteRemoveRisk(url);
			if (res) {
	            node.unselect();
	            Ext.fly(node.ui.elNode).ghost('l', {
	                callback: node.remove, scope: node, duration: .4
	            });
				//currentTab = Ext.getCmp('tab_' + node.id);
				//if(currentTab)
				//	currentTab.close();
				this.viewer.removeTab(node);
			}
        }
    },

	remoteRemoveRisk: function(url) {
		var result = false;
		$.ajax({
		  type: 'delete',
		  url: url,
		  async: false,
		  complete: function(xml) {
				if(xml.status != 204){
					Ext.MessageBox.alert('Error', 'No se pudo crear o editar el riesgo');
					result = false;
				} else {
					//Ext.MessageBox.alert('Exito', 'El riesgo fue eliminado');
					result = true;
				}
		  }
		});
		return result;
	},

    addRisk : function(attrs, inactive, preventAnim){
        var exists = this.getNodeById(attrs.url);
        if(exists){
            if(!inactive){
                exists.select();
                exists.ui.highlight();
            }
            return;
        }
        Ext.apply(attrs, {
            iconCls: 'feed-icon',
            leaf:true,
            cls:'feed',
            id: attrs.url
        });
        var node = new Ext.tree.TreeNode(attrs);
        this.risks.appendChild(node);
		this.newIndex++;
        if(!inactive){
            if(!preventAnim){
                Ext.fly(node.ui.elNode).slideIn('l', {
                    callback: node.select, scope: node, duration: .4
                });
            }else{
                node.select();
            }
        }
        return node;
    },


    afterRender : function(){
        RiskPanel.superclass.afterRender.call(this);
        this.el.on('contextmenu', function(e){
            e.preventDefault();
        });
    }
});